import React, { useEffect, useState } from "react";
import { Table, Button, Input, Image, Switch, Space, Modal } from "antd";
import sendFetch from "@/fetch";
import "@/assets/styles/Manager.scss";
import sha256 from "crypto-js/sha256";

export default function UserList() {
  const { Column } = Table;

  interface DataType {
    key: React.Key;
    avatar: string;
    name: string;
    email: string;
    is_locked: boolean;
    created_at: string;
  }

  const [data, setData] = useState<DataType[]>([]);
  const [sourceData, setSData] = useState([]);
  const [searchName, setSName] = useState("");
  const [searchEmail, setSEmail] = useState("");
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [newname, setNewName] = useState("");
  const [newemail, setNewEmail] = useState("");
  const [newpsw, setNewPsw] = useState("");
  const [openEdit, setOpenEdit] = useState(false);
  const [confirmLoadingEdit, setConfirmLoadingEdit] = useState(false);
  const [newnameEdit, setNewNameEdit] = useState("");
  const [newemailEdit, setNewEmailEdit] = useState("");
  const [newpswEdit, setNewPswEdit] = useState("");
  const [idEdit, setidEdit] = useState<React.Key>(0);

  const getUserData = async () => {
    sendFetch(`/manager/getUserInfo`).then((res:any) => {
      setData(res.data);
      setSData(res.data);
    });
  };

  useEffect(() => {
    getUserData();
  }, []);

  const banUser = (id: number|React.Key, isBan: boolean, index: number) => {
    return () => {
      let params = { id: id, isBan: isBan };
      sendFetch(`/manager/banUser`, params, "GET").then((res:any) => {
        if (res.code == 3001) {
          let t: DataType[] = [...data];
          t[index].is_locked = isBan;
          setData(t);
        }
      });
    };
  };

  const searchSourceData = () => {
    sendFetch(`/manager/getUserInfo`).then((res:any) => {
      setSData(res.data);
    });
    let y: DataType[] = [];
    sourceData.forEach((value:DataType, _) => {
      if (value.name.includes(searchName) && value.email.includes(searchEmail))
        y.push(value);
    });
    setData(y);
  };

  const addUser = () => {
    setOpen(true);
  };

  const handleOk = () => {
    setConfirmLoading(true);
    sendFetch(
      `/manager/addUser`,
      { name: newname, email: newemail, password: sha256(newpsw).toString() },
      "POST"
    ).then(() => {
      document.getElementById("nn").value = "";
      document.getElementById("ne").value = "";
      document.getElementById("np").value = "";
      getUserData();
      setConfirmLoading(false);
      setOpen(false);
    });
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const handleOkEdit = () => {
    setConfirmLoadingEdit(true);
    sendFetch(
      `/manager/editUser`,
      {
        id: idEdit,
        name: newnameEdit,
        email: newemailEdit,
        password: sha256(newpswEdit).toString(),
      },
      "POST"
    ).then(() => {
      getUserData();
      setConfirmLoadingEdit(false);
      setOpenEdit(false);
    });
  };

  const handleCancelEdit = () => {
    setOpenEdit(false);
  };

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          background: "#fff",
          padding: "3vh",
          margin: "3vh 0",
        }}
      >
        <div style={{ display: "flex" }}>
          <div style={{ display: "flex", alignItems: "center" }}>
            <p style={{ width: "4vw" }}>姓名：</p>
            <Input
              id="sn"
              type="text"
              onBlur={(e) => {
                setSName(e.target.value);
              }}
            />
          </div>
          <div
            style={{ display: "flex", alignItems: "center", marginLeft: "3vh" }}
          >
            <p style={{ width: "4vw" }}>邮箱：</p>
            <Input
              id="se"
              type="text"
              onBlur={(e) => {
                setSEmail(e.target.value);
              }}
            />
          </div>
        </div>
        <div>
          <Button
            onClick={() => {
              setSName("");
              setSEmail("");
              document.getElementById("sn").value = "";
              document.getElementById("se").value = "";
            }}
          >
            重置
          </Button>
          <Button
            type="primary"
            style={{ margin: "0 1vw" }}
            onClick={searchSourceData}
          >
            搜索
          </Button>
          <Button type="primary" onClick={addUser}>
            添加用户
          </Button>
          <Modal
            title="添加用户"
            open={open}
            onOk={handleOk}
            confirmLoading={confirmLoading}
            onCancel={handleCancel}
          >
            姓名：
            <Input
              type="text"
              id="nn"
              onBlur={(e) => {
                setNewName(e.target.value);
              }}
            />
            邮箱：
            <Input
              type="text"
              id="ne"
              onBlur={(e) => {
                setNewEmail(e.target.value);
              }}
            />
            密码：
            <Input
              type="text"
              id="np"
              onBlur={(e) => {
                setNewPsw(e.target.value);
              }}
            />
          </Modal>
        </div>
      </div>
      <div>
        <Table dataSource={data}>
          <Column
            width={30}
            title="头像"
            dataIndex="avatar"
            key="avatar"
            render={(_, record: DataType) => (
              <>
                <Image
                  style={{
                    height: "5vh",
                    width: "5vh",
                    borderRadius: "50%",
                    overflow: "hidden",
                  }}
                  src={record.avatar || "default"}
                  fallback=""
                />
              </>
            )}
          />
          <Column title="姓名" dataIndex="name" key="name" />
          <Column title="邮箱" dataIndex="email" key="email" />
          <Column
            title="是否禁用"
            dataIndex="is_locked"
            key="is_locked"
            render={(_, record: DataType, index) => (
              <>
                <Switch
                  checkedChildren="启用"
                  unCheckedChildren="禁用"
                  checked={!record.is_locked}
                  onClick={banUser(record.key, !record.is_locked, index)}
                />
              </>
            )}
          />
          <Column title="创建时间" dataIndex="created_at" key="created_at" />
          <Column
            title="操作"
            key="action"
            render={(value, record: DataType) => (
              <Space size="middle">
                <button
                  className="hrefButton"
                  onClick={() => {
                    setOpenEdit(true);
                    setNewNameEdit(record.name);
                    setNewEmailEdit(record.email);
                    setNewPswEdit("");
                    setidEdit(record.key);
                  }}
                >
                  编辑
                </button>
                <button
                  className="hrefButton"
                  onClick={() => {
                    sendFetch(
                      `/manager/deleteUser`,
                      { id: record.key },
                      "GET"
                    ).then(() => {
                      getUserData();
                    });
                  }}
                >
                  删除
                </button>
              </Space>
            )}
          />
        </Table>
      </div>
      <Modal
        title="修改用户"
        open={openEdit}
        onOk={handleOkEdit}
        confirmLoading={confirmLoadingEdit}
        onCancel={handleCancelEdit}
      >
        姓名：
        <Input
          type="text"
          value={newnameEdit}
          onChange={(e) => {
            setNewNameEdit(e.target.value);
          }}
        />
        邮箱：
        <Input
          type="text"
          value={newemailEdit}
          onChange={(e) => {
            setNewEmailEdit(e.target.value);
          }}
        />
        密码：
        <Input
          type="text"
          value={newpswEdit}
          onChange={(e) => {
            setNewPswEdit(e.target.value);
          }}
        />
      </Modal>
    </div>
  );
}
